<?php
session_start();
//print_r($_POST);
//session_start();
	$con = mysql_connect("127.0.0.1","root","");
	  
	if (!$con) {
		error_log("Could not connect: " . mysql_error());
	}

	mysql_select_db("yeoldeguilde", $con);

$user = '';
$msg = '';
$response = array();


if (isset($_POST['user']) && isset($_POST['pass'])) {
	
	$response['code'] = doLogin();		
	//$_SESSION['code'] = $response['code'];
	$response['msg'] = $msg;
	$response['user'] = $user;
	die ( json_encode($response) );
}

if (isset($_POST['logout'])) {
	$_SESSION['code'] = 0;
	unset($_SESSION['user']);
	$msg = 'All your dreams are coming true...';
	$response['code'] = 0;
	$response['msg'] = $msg;
	$response['user'] = $user;
	die ( json_encode($response) );
}

// No previous login detected
// TODO: cookie support
if (!isset($_SESSION['code'])  || !isset($_SESSION['user'])) {		
	$response['code'] = 0;
	$msg = 'Who you?';
	$response['msg'] = $msg;
	$response['user'] = $user;
	die ( json_encode($response) );
}

// If already logged in:
// Looks for a password change on first-time logins otherwise:
// Return stored username otherwise
if (isset($_SESSION['code'])) {
	if ($_SESSION['code'] == 1) {		
		$response['code'] = 1;
		$response['msg'] = $msg;
		$response['user'] = $_SESSION['user'];
		die ( json_encode($response) );
	} else if ($_SESSION['code'] == 2) { // first-time login case
		$user = $_SESSION['user'];
		if ( changePassword() ) {
			// password change successful, normal login recorded
			$response['code'] = 1;
			$response['msg'] = $msg;
			$response['user'] = $user;
			die ( json_encode($response) );
		} else {
			// password change unsuccessful, reset saved user data
			$response['code'] = 0;
			$response['msg'] = $msg;
			$response['user'] = '';
			unset( $_SESSION['user'] );
			die ( json_encode($response) );
		}
	}
}



mysql_close($con);
echo json_encode($response);

if (isset($_SESSION['user'])) {


	} else {

	}
/* Response codes output
// 0 - invalid login
// 1 - successful login
// 2 - successful login / temporary password change prompt
*/
function doLogin() {
	global $user, $msg, $con;
	
	if (isset($_POST['user']) && isset($_POST['pass'])) {
		if (($_POST['user'] == "") || ($_POST['pass'] == "")) {
			$msg = "Must enter a user name AND password, dumy [sic].";
			return 0;			
		} else {
		
			$query = 'SELECT * FROM members WHERE name="'.$_POST['user'].'" AND password="'.md5($_POST['pass']).'"';
			
			$result = mysql_query($query,  $con);			
			$numResults = mysql_num_rows($result);
			
			if($numResults < 1) {
				$msg = "Please login! =D";
				//Print_r($_POST);
				return 0;
			} else {				
				
				$row = mysql_fetch_array($result);
				$user = $row['name'];
				
				$_SESSION['user'] = $user;
				if ($row['newUser'] == 0) {
					$msg = "Login Successful! Go hog wild!";
					$_SESSION['code'] = 1;
					return 1;
				} else {
					$msg = "Login Successful! MUST NOW CHANGE DEFAULT PASSWORD YOU FOOL!";
					$_SESSION['code'] = 2;
					return 2;
				}
			}			
		}
	}
	
}

// returns true on success \ false on failure
function changePassword() {
	global $user, $msg, $con;
	
	//print_r($_POST);
	if (!isset($_POST['pass0'])) {
		$msg = "You must change your password to remain logged in, try again!";
		$_SESSION['code'] = 0;
		return false;
	}
	
	if ($_POST['pass0'] !== $_POST['pass1']) {
		$msg = "Error, passwords may not have matched...? @_@";
		$_SESSION['code'] = 0;
		return false;
	}
	
	$query = "UPDATE members SET password = '".md5($_POST['pass0']). "' WHERE name = '".$user."'";
	//echo $query;
	if (!mysql_query($query,  $GLOBALS['con'])) {
		$_SESSION['code'] = 0;
		$msg = 'Error: ' . mysql_error() . "<p>Query string:".$query."</p>";
		return false;
		//echo 'Error: ' . mysql_error()."\n";
	}	
	$query = "UPDATE members SET newUser = '0' WHERE name = '".$user."'";
	if (!mysql_query($query,  $GLOBALS['con'])) {
		$_SESSION['code'] = 0;
		$msg = 'Error: ' . mysql_error() . "<p>Query string:".$query."</p>";
		return false;
		//echo 'Error: ' . mysql_error()."\n";
	}	
	$_SESSION['code'] = 1;	
	$msg = "Password updated successful for all I know...";
	return true;
}



?>